function initLjEvent() {
    $(".SysPageConfigEditBtn").on("click", function () {
        let pageCode = $(".SysPageConfigEditBtn").attr("pageCode");
        let ljUrl = "/sys/page/config/edit?pageCode=" + pageCode;
        let values = {};
        modifyVerf(values);
        if (ljUrl.indexOf("?") > 0) {
            ljUrl = ljUrl + "&cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        } else {
            ljUrl = ljUrl + "?cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        }
        let fields = '';
        $(".SysPageConfigEditTable th").each(function () {
            var spf = $(this).attr("spf");
            if (fields == '') {
                fields = fields + spf;
            } else {
                fields = fields + "," + spf;
            }
        });
        ljUrl = ljUrl + "&fields=" + fields;
        $.ajax({
            url: ljUrl,
            type: 'GET',
            cache: false,
            data: {},
            timeout: 1000 * 20,
            success: function (data) {
                layer.closeAll();
                layer.open({
                    type: 1,
                    title: '页面配置',
                    shadeClose: false,
                    resize: true,
                    shade: [0.8, '#393D49'],
                    maxmin: true,
                    area: ['80%', '80%'],
                    content: data
                });
            },
            error: function (xhr, status, error) {
                swal({
                    title: "请求页面异常:" + xhr.status,
                    text: xhr.responseText,
                    type: "error"
                });
                return;
            }
        });
    });
    // 弹出框
    $("[target='ljOpenCon']").on("click", function () {
        let tid = $(".ljTr.success").attr("tid");
        let ljUrl = $(this).attr("ljUrl");
        if (!ljUrl) {
            return;
        }
        if (ljUrl.indexOf("{tid}") > 0 && (tid === undefined || tid === '')) {
            swal({
                title: "温馨提示",
                text: "请选择您要操作的数据",
                type: "warning"
            });
            return;
        }
        ljUrl = ljUrl.replace(new RegExp("\\{tid\\}", "g"), tid);
        let title = $(this).attr("title").replace(new RegExp("\\{tid\\}", "g"), tid);
        let ljWidth = $(this).attr("ljWidth");
        if (!ljWidth) {
            ljWidth = '90%';
        }
        let ljHeight = $(this).attr("ljHeight");
        if (!ljHeight) {
            ljHeight = '90%';
        }
        let values = {};
        modifyVerf(values);
        if (ljUrl.indexOf("?") > 0) {
            ljUrl = ljUrl + "&cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        } else {
            ljUrl = ljUrl + "?cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        }
        $.ajax({
            url: ljUrl,
            type: 'GET',
            cache: false,
            data: {},
            timeout: 1000 * 20,
            success: function (data) {
                layer.closeAll();
                layer.open({
                    type: 1,
                    title: title,
                    shadeClose: false,
                    resize: true,
                    shade: [0.8, '#393D49'],
                    maxmin: true,
                    area: [ljWidth, ljHeight],
                    content: data
                });
            },
            error: function (xhr, status, error) {
                swal({
                    title: "请求页面异常:" + xhr.status,
                    text: xhr.responseText,
                    type: "error"
                });
                return;
            }
        });
    });
    // adjx请求
    $("[target='ljAjaxTodo']").on("click", function () {
        let tid = $(".ljTr.success").attr("tid");
        let title = $(this).attr("title").replace(new RegExp("\\{tid\\}", "g"), tid);
        let ljUrl = $(this).attr("ljUrl");
        if (ljUrl.indexOf("{tid}") > 0 && (tid === undefined || tid === '')) {
            swal({
                title: "温馨提示",
                text: "请选择您要操作的数据",
                type: "warning"
            });
            return;
        }
        ljUrl = ljUrl.replace(new RegExp("\\{tid\\}", "g"), tid);
        let values = {};
        modifyVerf(values);
        if (ljUrl.indexOf("?") > 0) {
            ljUrl = ljUrl + "&cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        } else {
            ljUrl = ljUrl + "?cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        }
        let callback = $(this).attr("callback");
        swal({
            title: title,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "提交",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            if (!ljUrl) {
                return;
            }
            let $callback = callback || ajaxDoneRefresh;
            if (!$.isFunction($callback)) $callback = eval('(' + callback + ')');
            $.ajax({
                type: 'POST',
                url: ljUrl,
                dataType: "json",
                cache: false,
                success: $callback,
                error: function (xhr, status, error) {
                    swal({
                        title: "请求页面异常:" + xhr.status,
                        text: xhr.responseText,
                        type: "error"
                    });
                    return;
                }
            });
        });
    });
    // 局部页面刷新
    $("[target='ljDivSerach']").on("click", function () {
        let tid = $(".ljTr.success").attr("tid");
        let rel = $(this).attr("rel");
        let ljUrl = $(this).attr("ljUrl");
        if (ljUrl.indexOf("{tid}") > 0 && (tid === undefined || tid === '')) {
            swal({
                title: "温馨提示",
                text: "请选择您要操作的数据",
                type: "warning"
            });
            return;
        }
        ljUrl = ljUrl.replace(new RegExp("\\{tid\\}", "g"), tid);
        if ($(rel).length <= 0) {
            return;
        }
        let values = {};
        modifyVerf(values);
        if (ljUrl.indexOf("?") > 0) {
            ljUrl = ljUrl + "&cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        } else {
            ljUrl = ljUrl + "?cmd5=" + values.cmd5;
            ljUrl = ljUrl + "&uid=" + values.uid;
            ljUrl = ljUrl + "&randomData=" + values.randomData;
        }
        $.ajax({
            url: ljUrl,
            type: 'GET',
            cache: false,
            data: {},
            timeout: 1000 * 20,
            success: function (data) {
                $(rel).html(data);
            },
            error: function (xhr, status, error) {
            }
        });
    });
    // 表格组件选择
    $(".ljTr").on("click", function () {
        $(".ljTr").removeClass("success").addClass("warning");
        $(this).removeClass("warning").addClass("success");
    });
    // 排序条件
    $(".thsort").on("click", function () {
        let sortId = $(this).attr("th-sort-id");
        let sortOrder = $(this).attr("th-sort-order");
        $("input[name='orderField']").val(sortId);
        if ("" === sortOrder) {
            $("input[name='orderDirection']").val("asc");
        } else if ("asc" == sortOrder) {
            $("input[name='orderDirection']").val("desc");
        } else {
            $("input[name='orderDirection']").val("asc");
        }
        $("#pagerForm").submit();
    });
}

$(function () {
    $(".chosen-select").chosen();
    //日期范围限制
    if ($("#ts").length > 0) {
        var ts = {
            elem: '#ts',
            format: 'YYYY-MM-DD hh:mm:ss',
            istime: true,
            istoday: true
        };
        laydate(ts);
    }
    if ($("#te").length > 0) {
        var te = {
            elem: '#te',
            format: 'YYYY-MM-DD hh:mm:ss',
            istime: true,
            istoday: true
        };
        laydate(te);
    }
    $(".ljLayerDate").each(function () {
        var elem = $(this).attr("elem");
        var format = $(this).attr("format");
        var ljLayerDate = {
            elem: elem,
            format: format,
            istime: true,
            istoday: true
        };
        laydate(ljLayerDate);
    });
    $(".ljLayerDay").each(function () {
        var elem = $(this).attr("elem");
        var format = $(this).attr("format");
        var ljLayerDate = {
            elem: elem,
            format: format,
            istime: false,
            istoday: true
        };
        laydate(ljLayerDate);
    });
    //全屏组件
    $('#fullPage').on('click', function () {
        if (screenfull.enabled) {
            screenfull.toggle();
        } else {
            alert('浏览器不支持全屏显示');
        }
    });
    $('.btnPageRefresh').on('click', function () {
        window.location.reload();
    });
    $('.btnPagerForm').on('click', function () {
        $("#pagerForm").submit();
    });
    $('.btnPagerFormMore').on('click', function () {
        var isMore = $(this).attr("isMore");
        if (isMore == undefined || isMore == 0) {
            $("#isMore").val(1);
            $("#pagerForm").submit();
        } else {
            $("#isMore").val(0);
            $("#pagerForm").submit();
        }
    });

    // 消息配置信息
    toastr.options = {
        "closeButton": true,
        "debug": true,
        "progressBar": true,
        "positionClass": "toast-bottom-full-width",
        "showDuration": "100",
        "hideDuration": "100",
        "timeOut": "5000",
        "extendedTimeOut": "5000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    // 表单校验
    $.validator.setDefaults({
        errorPlacement: function (error, element) {
            if (element.is(":radio")) {
                error.appendTo(element.parent().next().next());
            } else if (element.is(":checkbox")) {
                error.appendTo(element.next());
            } else {
                element.before(error);
            }
        }
    });
    $("[layoutH]").layoutH();
    initLjEvent();
});

function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;

    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

// ajax请求回调
function ajaxDoneRefresh(json) {
    if (json.statusCode === '300') {
        swal({
            title: "提交失败",
            text: json.message,
            type: "error"
        });
        return;
    } else if (json.statusCode === '301') {
        swal({
            title: "提交无权限",
            text: json.message,
            type: "warning"
        });
        return;
    } else if (json.statusCode === '200') {
        swal({
            title: "提交成功", text: json.message, type: "success"
        }, function (isConfirm) {
            window.location.reload();
        });
    }
}

function ajaxDoneShow(json) {
    if (json.statusCode === '300') {
        swal({
            title: "提交失败",
            text: json.message,
            type: "error"
        });
        return;
    } else if (json.statusCode === '301') {
        swal({
            title: "提交无权限",
            text: json.message,
            type: "warning"
        });
        return;
    } else if (json.statusCode === '200') {
        swal({
                title: "提交成功",
                text: json.message,
                type: "success"
            },
            function (isConfirm) {
                window.location.reload();
            });
    }
}

/**
 * 页面刷新返回
 */
function pageRefresh(json) {
    //疯狂模式，关闭所有层
    layer.closeAll();
    if (json.statusCode == '300') {
        swal({
            title: "提交失败",
            text: json.message,
            type: "error"
        });
        return;
    } else if (json.statusCode == '301') {
        swal({
            title: "提交无权限",
            text: json.message,
            type: "warning"
        });
        return;
    } else if (json.statusCode == '200') {
        window.location.reload();
    }
}

/**
 * 添加KEY信息
 */
function modifyVerf(values) {
    var rondomData = uuid(16, 16);
    var uid = '';
    var ClientDigest = '';
    var browser = DetectBrowser();
    if (browser != "Unknown") {
        createElementNT199();
        var create = DetectNT199Plugin();
        if (create != false) {
            if (1 <= NT199_Find()) {
                var retVal = NT199_CheckPassword("12345678");
                if (retVal == 0) {
                    uid = NT199_GetHardwareId();
                    var randomMessageFromServer = rondomData;
                    ClientDigest = NT199_Sha1WithSeed(randomMessageFromServer);
                }
            }
        }
    }
    values.cmd5 = ClientDigest;
    values.uid = uid;
    values.randomData = rondomData;
}

function moreConditon(isMore) {
    if (isMore == undefined || isMore == 0) {
        $("#isMore").val(1);
        $("#pagerForm").submit();
    } else {
        $("#isMore").val(0);
        $("#pagerForm").submit();
    }
}

/**
 * 普通ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 */
function validateCallback(form, callback) {
    var $form = $(form);
    if (!$form.valid()) {
        return false;
    }
    var _submitFn = function () {
        $form.find(':focus').blur();
        $.ajax({
            type: form.method || 'POST',
            url: $form.attr("action"),
            data: $form.serializeArray(),
            dataType: "json",
            cache: false,
            success: callback,
            error: function (xhr, status, error) {
                swal({
                    title: "请求数据异常:" + xhr.status,
                    text: xhr.responseText,
                    type: "error"
                });
                return;
            }
        });
    };
    _submitFn();
    return false;
}

/**
 * 带文件上传的ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 */
function iframeCallback(form, callback) {
    var $form = $(form);
    var $iframe = $("#callbackframe");
    if (!$form.valid()) {
        return false;
    }
    if ($iframe.size() == 0) {
        $iframe = $("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
    }
    if (!form.ajax) {
        $form.append('<input type="hidden" name="ajax" value="1" />');
    }
    form.target = "callbackframe";
    $form.find(':focus').blur();
    _iframeResponse($iframe[0], callback);
}

function _iframeResponse(iframe, callback) {
    var $iframe = $(iframe), $document = $(document);
    $document.trigger("ajaxStart");
    $iframe.bind("load", function (event) {
        $iframe.unbind("load");
        $document.trigger("ajaxStop");
        if (iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
            iframe.src == "javascript:'<html></html>';") {
            return;
        }
        var doc = iframe.contentDocument || iframe.document;
        if (doc.readyState && doc.readyState != 'complete') return;
        if (doc.body && doc.body.innerHTML == "false") return;
        var response;
        if (doc.XMLDocument) {
            response = doc.XMLDocument;
        } else if (doc.body) {
            try {
                response = $iframe.contents().find("body").text();
                response = jQuery.parseJSON(response);
            } catch (e) {
                response = doc.body.innerHTML;
            }
        } else {
            response = doc;
        }
        callback(response);
    });
}

(function ($) {
    $.fn.extend({
        layoutH: function ($refBox) {
            return this.each(function () {
                let $this = $(this);
                let iRefH = $(window).height();
                let iLayoutH = parseInt($this.attr("layoutH"));
                let iH = iRefH - iLayoutH > 50 ? iRefH - iLayoutH : 50;
                $this.height(iH).css("overflow", "auto");
            });
        }
    });
})(jQuery);

/**
 * @author ZhangHuihua@msn.com
 *
 */
const DWZ = {
    isOverAxis: function (x, reference, size) {
        return (x > reference) && (x < (reference + size));
    }, isOver: function (y, x, top, left, height, width) {
        return this.isOverAxis(y, top, height) && this.isOverAxis(x, left, width);
    }, obj2str: function (o) {
        let r = [];
        if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
        if (typeof o == "object") {
            if (!o.sort) {
                for (let i in o) r.push(i + ":" + DWZ.obj2str(o[i]));
                if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                    r.push("toString:" + o.toString.toString());
                }
                r = "{" + r.join() + "}"
            } else {
                for (let i = 0; i < o.length; i++) {
                    r.push(DWZ.obj2str(o[i]));
                }
                r = "[" + r.join() + "]"
            }
            return r;
        }
        return o.toString();
    },
    jsonEval: function (data) {
        try {
            if ($.type(data) == 'string')
                return eval('(' + data + ')');
            else return data;
        } catch (e) {
            return {};
        }
    }
};

/**
 * You can use this map like this:
 * var myMap = new Map();
 * myMap.put("key","value");
 * var key = myMap.get("key");
 * myMap.remove("key");
 */
function Map() {
    this.elements = new Array();
    this.size = function () {
        return this.elements.length;
    }
    this.isEmpty = function () {
        return (this.elements.length < 1);
    }
    this.clear = function () {
        this.elements = new Array();
    }
    this.put = function (_key, _value) {
        this.remove(_key);
        this.elements.push({key: _key, value: _value});
    }
    this.remove = function (_key) {
        try {
            for (let i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            return false;
        }
        return false;
    }
    this.get = function (_key) {
        try {
            for (let i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    return this.elements[i].value;
                }
            }
        } catch (e) {
            return null;
        }
    }
    this.element = function (_index) {
        if (_index < 0 || _index >= this.elements.length) {
            return null;
        }
        return this.elements[_index];
    }
    this.containsKey = function (_key) {
        try {
            for (let i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    return true;
                }
            }
        } catch (e) {
            return false;
        }
        return false;
    }
    this.values = function () {
        let arr = new Array();
        for (let i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].value);
        }
        return arr;
    }
    this.keys = function () {
        let arr = new Array();
        for (let i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].key);
        }
        return arr;
    }
}
